/**
 * SparePartServiceImpl.java
 * @author
 * 作者 屈甲康 
 */
package org.jackysoft.service.impl;


import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jackysoft.entity.Department;
import org.jackysoft.entity.SparePart;
import org.jackysoft.service.AbstractStringIdServiceImpl;
import org.jackysoft.service.SparePartService;
import org.jackysoft.util.Page;
import org.joda.time.DateTime;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
public class SparePartServiceImpl 
extends AbstractStringIdServiceImpl<SparePart>
implements SparePartService {
    /**
	 * 
	 */
	private static final long serialVersionUID = 4180582517926129186L;
	final static Log logger = LogFactory.getLog(SparePartServiceImpl.class);

	public SparePartServiceImpl(){
	    this.type = SparePart.class;
	}

	@Override
	public Page statByDate(DateTime date) throws DataAccessException {
		
		String hql = String
				.format("select new org.jackysoft.service.impl.SparePartVo(count(m.id) as count ,m.owner as owner) " +
						"from %s m where year(m.outDate)=%d and month(m.outDate)=%d " +
						"group by m.owner " +
						"order by m.outDate desc ",
						table() 
						, date.getYear()
		        		, date.getMonthOfYear()
						
						);
        Page pageData = new Page();
        pageData.setPage(0);
        pageData.setOffset(20);
        List itr = query(hql).list();
		pageData.setRows(itr);
        return pageData;
	}

	@Override
	public Page statByOwner(Department owner,DateTime date, Integer page, Integer offset)
			throws DataAccessException {
		
		String hql = String.format("select count(*) from %s m where year(m.outDate)=%d and month(m.outDate)=%d and  m.owner.id='%s'"
        		, table()
        		, date.getYear()
        		, date.getMonthOfYear()
        		, owner.getId());
	    
		Page pageData = new Page();
		pageData.setPage(page);
		pageData.setOffset(offset);
		Object obj = query(hql).uniqueResult();
		pageData.setRecords(Integer.parseInt(obj.toString()));		
		hql = String.format("from %s m where year(m.outDate)=%d and month(m.outDate)=%d and  m.owner.id='%s' order by m.outDate desc",
				table()
				, date.getYear()
        		, date.getMonthOfYear()
				, owner.getId());
		List itr = query(hql).setFirstResult(pageData.getFrom()).setMaxResults(offset).list();
		pageData.setRows(itr);
		return pageData;
	}	
		
}